<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间查询">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="会员姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入会员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队查询" prop="deptId">
        <treeselect style="width: 215px" v-model="queryParams.deptId" :options="deptOptions" :show-count="true"
                    placeholder="请选择团队"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="multiple"
          @click="handleExchange"
          v-hasPermi="['data:score:exchange']"
        >选择兑换
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAllExchange"
          v-hasPermi="['data:score:exchange']"
        >全部兑换
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['data:score:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe border v-loading="loading" :data="scoreList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员编号" align="center" prop="userId" width="80"/>
      <el-table-column label="会员姓名" align="center" prop="nickName"/>
      <el-table-column label="查询时间段积分" align="center" prop="score"/>
      <el-table-column label="查询时间段兑换积分" align="center" prop="timeScore"/>
      <el-table-column label="当前已兑换积分" align="center" prop="scoreUse"/>
      <el-table-column label="当前剩余积分" align="center" prop="scoreCurrent"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            plain
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="handleDetail(scope.row)"
          >查看明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 明细列表 -->
    <el-dialog title="积分明细" :visible.sync="scoreOpen" width="1200px" append-to-body>
      <el-form :model="queryDetailParams" ref="queryDetailParams" size="small" :inline="true"
               label-width="68px">
        <el-form-item label="时间查询">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            readonly
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="会员姓名" prop="userLevel">
          <el-input
            v-model="queryDetailParams.nickName"
            placeholder="请输入会员姓名"
            readonly
          />
        </el-form-item>
        <el-form-item label="积分类型" prop="scoreType">
          <el-select @change="changeScoreType()" v-model="queryDetailParams.scoreType" placeholder="请选择积分类型" clearable>
            <el-option
              v-for="dict in dict.type.sys_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" icon="el-icon-download" size="mini" @click="handleDetailExport">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table stripe border v-loading="detailLoading" :data="scoreDetailList">
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="主键" align="center" prop="id" v-if="false"/>
        <el-table-column label="会员编号" align="center" prop="userId" width="80"/>
        <el-table-column label="会员姓名" align="center" prop="nickName"/>
        <el-table-column label="积分类型" align="center" prop="scoreType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_type" :value="scope.row.scoreType"/>
          </template>
        </el-table-column>
        <el-table-column label="积分" align="center" prop="score"/>
        <el-table-column label="当前积分" align="center" prop="scoreCurrent"/>
        <el-table-column label="积分描述" align="center" show-overflow-tooltip prop="scoreDesc" min-width="400"/>
      </el-table>
      <pagination
        v-show="detailTotal>0"
        :total="detailTotal"
        :page.sync="queryDetailParams.pageNum"
        :limit.sync="queryDetailParams.pageSize"
        @pagination="getScoreDetailList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {exchangeListScore, exchangeScore, listScore} from "@/api/data/score";
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "Exchange",
  dicts: ['sys_type'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 积分记录表格数据
      scoreList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        nickName: null,
        userIds: null,
      },
      // 表单参数
      form: {},
      // 代理树选项
      deptOptions: undefined,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 182);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一整年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 日期范围
      dateRange: [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')],
      // 是否显示积分明细弹出层
      scoreOpen: false,
      // 明细总条数
      detailTotal: 0,
      // 积分记录表格数据
      scoreDetailList: [],
      // 查询明细参数
      queryDetailParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        nickName: null,
        scoreType: null,
      },
      // 明细遮罩层
      detailLoading: true
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 切换积分类型 */
    changeScoreType() {
      this.queryDetailParams.pageNum = 1
      this.getScoreDetailList()
    },
    /** 查询明细 */
    handleDetail(row) {
      this.scoreOpen = true
      this.scoreDetailList = []
      this.detailTotal = 0
      this.queryDetailParams.pageNum = 1
      this.queryDetailParams.userId = row.userId
      this.queryDetailParams.nickName = row.nickName
      this.queryDetailParams.scoreType = null
      this.getScoreDetailList()
    },
    /** 明细列表 */
    getScoreDetailList() {
      this.detailLoading = true;
      listScore(this.addDateRange(this.queryDetailParams, this.dateRange)).then(response => {
        this.scoreDetailList = response.rows;
        this.detailTotal = response.total;
        this.detailLoading = false;
      });
    },
    /** 查询代理下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询积分记录列表 */
    getList() {
      this.loading = true;
      exchangeListScore(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.scoreList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        userId: null,
        nickName: null,
        score: null,
        scoreType: null,
        scoreDesc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 全部兑换按钮操作 */
    handleAllExchange() {
      this.queryParams.userIds = null
      exchangeScore(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.getList();
        this.$modal.msgSuccess("兑换成功");
      });
    },
    /** 选择兑换按钮操作 */
    handleExchange(row) {
      this.queryParams.userIds = row.userId || this.ids;
      exchangeScore(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.queryParams.userIds = null
        this.getList();
        this.$modal.msgSuccess("兑换成功");
      }).catch(
        this.queryParams.userIds = null
      );
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('data/score/exportExchange', {
        ...this.queryParams
      }, `scoreExchange_${new Date().getTime()}.xlsx`)
    },
    /** 导出按钮操作 */
    handleDetailExport() {
      this.download('data/score/export', {
        ...this.queryDetailParams
      }, `scoreDetail_${new Date().getTime()}.xlsx`)
    }
  }
}
;
</script>
